﻿
layui.define(['layer','form','util','upload'], function (exports) {

    var $ = layui.jquery
        , layer = layui.layer
        , form = layui.form
        , util = layui.util
        , device = layui.device()
        , upload = layui.upload;
    //阻止IE7以下访问
    if (device.ie) {
        layer.alert('请使用IE以外的浏览器');
    }

    layui.focusInsert = function (obj, str) {
        var result, val = obj.value;
        obj.focus();
        if (document.selection) { //ie
            result = document.selection.createRange();
            document.selection.empty();
            result.text = str;
        } else {
            result = [val.substring(0, obj.selectionStart), str, val.substr(obj.selectionEnd)];
            obj.focus();
            obj.value = result.join('');
        }
    };

    var gather = {
        //新消息通知
         newmsg: function () {
            if (layui.cache.user.uid !== -1) {
                getPost('/msg/msgcount', {
                    _: new Date().getTime()
                }, function (res) {
                    if (res.status === 0 && res.count > 0) {
                        var msg = $('<a class="nav-message" href="javascript:;" title="您有' + res.count + '条未阅读的消息">' + res.count + '</a>');
                        $('.nav-user').append(msg);
                        msg.on('click', function () {
                            getPost('/msg/read', {}, function (res) {
                                if (res.status === 0) {
                                    location.href = '/user/msg';
                                }
                            });
                        });
                    }
                });
            }
            return arguments.callee;
        }

        , cookie: function (e, o, t) {
            e = e || ""; var n, i, r, a, c, p, s, d, u; if ("undefined" == typeof o) { if (p = null, document.cookie && "" != document.cookie) for (s = document.cookie.split(";"), d = 0; d < s.length; d++)if (u = $.trim(s[d]), u.substring(0, e.length + 1) == e + "=") { p = decodeURIComponent(u.substring(e.length + 1)); break } return p } t = t || {}, null === o && (o = "", t.expires = -1), n = "", t.expires && ("number" == typeof t.expires || t.expires.toUTCString) && ("number" == typeof t.expires ? (i = new Date, i.setTime(i.getTime() + 864e5 * t.expires)) : i = t.expires, n = "; expires=" + i.toUTCString()), r = t.path ? "; path=" + t.path : "", a = t.SrBBSPro ? "; SrBBSPro=" + t.SrBBSPro : "", c = t.secure ? "; secure" : "", document.cookie = [e, "=", encodeURIComponent(o), n, r, a, c].join("");
        }   

         ,getOption:function (adr, kind, eleId, eleId2) {
            var html1 = '<dd lay-value="" >' + "请选择" + '</dd>';
            var html2 = '<option value="" >' + "请选择" + '</option>';
            getPost(adr, {
                kind: kind
            }, function (res) {
                if (res.status === 0) {
                    var names = res.msg;
                    for (var i = 0; i < names.length; i++) {
                        html1 += '<dd lay-value="' + names[i].val + '">' + names[i].text + '</dd>';
                        html2 += '<option value="' + names[i].val + '">' + names[i].text + '</option>';
                    }
                    $("#" + eleId).next().children().eq(1).html(html1);
                    $("#" + eleId).html(html2);
                    if (eleId2 != undefined && eleId2 != "") {
                        $("#" + eleId2).next().children().eq(1).html(html1);
                        $("#" + eleId2).html(html2);
                    }
                    form.render();
                } else {
                    layer.msg(res.msg);
                }
            });
        }
    };

    //搜索
    $('.fly-search').submit(function () {
        var input = $(this).find('input'), val = input.val();
        if (val.replace(/\s/g, '') === '') {
            return false;
        }
    });

    //新消息通知
    gather.newmsg();

    //点击@
    $('body').on('click', '.fly-aite', function () {
        var othis = $(this), text = othis.text();
        if (othis.attr('href') !== 'javascript:;') {
            return;
        }
        text = text.replace(/^@|（[\s\S]+?）/g, '');
        othis.attr({
            href: '/jump/' + text
            , target: '_blank'
        });
    });

    //表单提交
    form.on('submit(*)', function (data) {
        var action = $(data.form).attr('action'), button = $(data.elem);
        console.log(action);
        getPost(action, data.field, function (res) {
            var end = function () {
                if (res.action) {
                    location.href = res.action;
                } else {
                    gather.form[action || button.attr('key')](data.field, data.form);
                }
            };
            if (res.status == 0) {
                button.attr('alert') ? layer.alert(res.msg, {
                    icon: 1,
                    time: 10 * 1000,
                    end: end
                }) : end();
            };
        });
        return false;
    });

    form.on('submit(add)', function (data) {
        var action = $(data.form).attr('action')
        $.post(action, data.field, function (res) {
            if (res.status == 1) {
                layer.msg(res.msg, { icon: 2 });
            } else {
                layer.msg(res.msg, { icon: 1, time: 1000 }, function (index) {
                    layer.close(index);
                    if (res.action) {
                        if (res.action.split("?").length > 1) {
                            var param = res.action.split("?")[1];
                            var val = {};
                            for (i = 0; i < param.split("&").length; i++) {
                                var item = param.split("&")[i];
                                val[item.split("=")[0]] = item.split("=")[1];
                            };
                            layui.data('model', {
                                key: 'model',
                                value: val
                            });
                            location.href = res.action.split("?")[0];
                        } else {
                            location.href = res.action;
                        } 
                    } else {
                        layer.msg(res.msg, { icon: 5 });
                    }
                });
            }
        }, 'json');
        return false;
    });


    //加载特定模块
    if (layui.cache.page && (layui.cache.page === 'post' || layui.cache.page === 'user')) {
        layui.use(layui.cache.page);
    }

    //右下角固定Bar
    util.fixbar({
        bar1: true
        , click: function (type) {
            if (type === 'bar1') {
                location.href = '/';
            }
        }
    });

    exports('common', gather);

});

